package com.ruoyi.quartz.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.RealNameAuth;
import com.ruoyi.bizsys.domain.UserFeedback;
import com.ruoyi.bizsys.mapper.RealNameAuthMapper;
import com.ruoyi.bizsys.service.IUserFeedbackService;
import com.ruoyi.common.config.EmailConfig;
import com.ruoyi.common.config.EmailRouteConfig;
import com.ruoyi.common.constant.EmailConstants;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.EmailUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.vo.EmailVo;
import com.ruoyi.quartz.util.EmailsTemplate;
import com.ruoyi.sms.common.Constants;
import com.ruoyi.system.service.impl.SysConfigServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 发送用户反馈邮件  每天执行一次
 */
@Slf4j
@AllArgsConstructor
@Component("sendEmail")
public class SendFeedBackEmail {
    @Autowired
    private IUserFeedbackService userFeedbackService;

    @Autowired
    private RealNameAuthMapper realNameAuthMapper;

    @Autowired
    private EmailRouteConfig emailRouteConfig;

    @Autowired
    private SysConfigServiceImpl sysConfigService;

    public void send() {
        log.info("邮件发送任务 Start >>>>>>>>>>");
        //查询出没有发送邮件的任务
        UserFeedback userFeedback = new UserFeedback();
        userFeedback.setState(Integer.parseInt(Constants.BIZ_STATUS_1));
        userFeedback.setIsSend(0);
        // 邮件模板
        String emailsContent = null;
        // 邮件标题
        String subject = sysConfigService.selectConfigByKey("subject");
        String lastName = null;
        // 查询出来当天 状态正常 没有发送邮件的反馈记录
        List<UserFeedback> userFeedbacks = userFeedbackService.selectDayUserFeedbackList(userFeedback);
        if (CollectionUtils.isEmpty(userFeedbacks)) {
            throw new BusinessException("发送的邮箱任务没有查询出来结果");
        }
        // 收集要更改状态的userid
        ArrayList<String> userIds = new ArrayList<>();
        for (int i = 0; i < userFeedbacks.size(); i++) {
            UserFeedback feedback = userFeedbacks.get(i);
            String operationType = feedback.getOperationType();
            String email = feedback.getEmail();
            //  邮箱校验  如果失败备注信息 更改状态
            if (!isEmail(email)) {
                feedback.setRemark("邮箱地址为：" + email + ",邮箱格式错误");
                feedback.setState(Integer.parseInt(Constants.BIZ_STATUS_0));
                userFeedbackService.updateByUserId(feedback);
                continue;
            }
            // 如果弹窗类型是授信拒绝或者是提现拒绝 查询出来last name
            if (EmailConstants.CREDIT_REJECTION.equals(operationType) || EmailConstants.WITHDRAWAL_REJECTION.equals(operationType)) {
                QueryWrapper<RealNameAuth> realNameAuthQueryWrapper = new QueryWrapper<>();
                realNameAuthQueryWrapper.select("last_name");
                realNameAuthQueryWrapper.eq("user_id", feedback.getUserId());
                RealNameAuth realNameAuth = realNameAuthMapper.selectOne(realNameAuthQueryWrapper);
                lastName = realNameAuth.getLastName();
            }
            //根据弹窗的类型  调用发送邮件接口
            //实名失败窗口
            switch (operationType) {
                case EmailConstants.REAL_FAILED:
                    emailsContent = EmailsTemplate.readEmailTemplate(emailRouteConfig.getBaseRoute() + emailRouteConfig.getEmailRealFail());
                    break;
                case EmailConstants.CREDIT_REJECTION:
                    emailsContent = EmailsTemplate.readEmailTemplate(emailRouteConfig.getBaseRoute() + emailRouteConfig.getEmailCreditRejection()).replace("{LastName}", lastName);
                    break;
                case EmailConstants.WITHDRAWAL_REJECTION:
                    emailsContent = EmailsTemplate.readEmailTemplate(emailRouteConfig.getBaseRoute() + emailRouteConfig.getEmailWithdrawalRejection()).replace("{LastName}", lastName);
                    break;
                case EmailConstants.CARD_FAILED:
                    emailsContent = EmailsTemplate.readEmailTemplate(emailRouteConfig.getBaseRoute() + emailRouteConfig.getEmailCardFailed());
                    break;
                default:
                    throw new BusinessException(RspEnmu.EMAIL_TYPE_NOEXIST);
            }
            try {
                EmailVo emailVo = EmailVo.builder()
                        .subject(subject)
                        .cc(new String[]{EmailConfig.getFeedBackAddress()})
                        .addressees(new String[]{email})
                        .feedBackEmailParam(emailsContent)
                        .build();
                String result = EmailUtils.sendfeedbackMailParameterAssemblyEmail(emailVo);
                JSONObject resultJson = JSONObject.parseObject(result);
                if ("200000".equals(resultJson.getString("code"))) {
                    userIds.add(feedback.getUserId());
                } else {
                    throw new BusinessException(RspEnmu.EMAil_SEND_FAILED);
                }
            } catch (Exception e) {
                log.error(">>>>>>>>>>定时任务调用发送邮件接口异常", e);
            }

        }
        // 批量一千条修改发送状态
        ArrayList<String> batchList = new ArrayList<>();
        if (StringUtils.isNotEmpty(userIds)) {
            for (int i = 0; i < userIds.size(); i++) {
                batchList.add(userIds.get(i));
                if ((i + 1) % 1000 == 0 || i == userIds.size() - 1) {
                    userFeedbackService.updateBatchByUserId(batchList);
                    batchList.clear();
                }
            }
        }
    }

    public boolean isEmail(String email) {
        if (null == email || "".equals(email)) {
            return false;
        }
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p = Pattern.compile(regEx1);
        Matcher m = p.matcher(email);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }

}
